package cn.thr.pethome.config;

import cn.thr.pethome.annotation.PreAuthorize;
import cn.thr.pethome.jwt.Payload;
import cn.thr.pethome.jwt.PayloadData;
import cn.thr.pethome.logininfo.domain.Logininfo;
import cn.thr.pethome.role.mapper.RoleMapper;
import cn.thr.pethome.role.service.IRoleService;
import cn.thr.pethome.user.domain.Employee;
import cn.thr.pethome.user.domain.User;
import cn.thr.pethome.user.service.IEmployeeService;
import cn.thr.pethome.util.JwtUtils;
import cn.thr.pethome.util.RsaUtils;
import org.apache.commons.compress.archivers.dump.DumpArchiveEntry;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 自己定义的登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private final String MSG = "{\"success\":false,\"msg\":\"noLogin\"}";
    private final String NO_PERMISSION = "{\"success\":false,\"msg\":\"NoPermission\"}";
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private RoleMapper roleMapper;

    @Value("${jwt.rsa.pub}")
    private String pub;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //真正业务逻辑实现
        //redisTemplate.opsForValue().get(Key????"")
        //前端传进来的token
        String toKen = request.getHeader("ToKen");
        if (toKen == null) {
            //ctrl + alt  + m 抽取方法
            setErrorMsg(response, MSG);
            return false;
        }
        //根据传进来的token 进行解析 有没有过期
        PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(pub).getFile());
        Payload<PayloadData> o = null;
        try {
            o = JwtUtils.getInfoFromToken(toKen, publicKey, PayloadData.class);
        } catch (Exception e) {
            setErrorMsg(response, MSG);
            return false;
        }
        //刷新token
        //过期时间
        Date expiration = o.getExpiration();
        //刷新时间
        DateTime refreshTime = new DateTime(expiration).minusMinutes(5);  //过期前多少分钟  倒计时
        //当前时间在刷新时间之后就要刷新一把
        if (refreshTime.isBefore(DateTime.now())) {
            setErrorMsg(response, MSG);
            //重新登录刷新token          response.getWriter().write("{\"success\":false,\"message\":\"noLogin\"}");
            return false;
        }

        //2.如果是后端员工employee来操作的时候，才需要校验资源的访问权限
        //2.1 哪些请求需要校验权限 （答：打了自定义注解PreAuthorize权限的方法）
        //获取你请求的那个接口的自定义注解
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
            //3.判断preAuthorize 是否有值
            if (preAuthorize == null) {
                //3.2 没有，放行  公共资源不需要校验权限
                return true;
            }
            //3.1 有，校验是否有权限访问
            String sn = preAuthorize.value();//需要校验当前登录人，是否有权限访问该资源
            if (!o.getUserInfo().getPermissions().contains(sn)) { //contains 包含的意思，有就是ture  如果没有权限就不能进去，有就直接走
                setErrorMsg(response, NO_PERMISSION); //没有权限就告诉没有权限
                return false;
            }
        }
        return true;
    }

    private void setErrorMsg(HttpServletResponse response, String msg) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        // 在外面写好在拷贝进去
        writer.write(msg);
        writer.close();
    }

    private Boolean redisToken(HttpServletRequest request, HttpServletResponse response, Object handler) {
        try {
            //真正业务逻辑实现
            //redisTemplate.opsForValue().get(Key????"")
            String toKen = request.getHeader("ToKen");
            if (toKen == null) {
                //ctrl + alt  + m 抽取方法
                setErrorMsg(response, MSG);
                return false;
            }
            Object o = redisTemplate.opsForValue().get(toKen);
            if (o == null) {
                setErrorMsg(response, MSG);
                return false;
            }
            //刷新
            redisTemplate.opsForValue().set(toKen, o, 30, TimeUnit.MINUTES);
            //直接再redis 里面去取  比在数据库里面快多了  LogininfoServiceImpl 刷新到了LogininfoServiceImpl 里面去了
            List<String> permissionsByRoleIds = (List<String>) redisTemplate.opsForValue().get(toKen + "permission");

            //2.如果是后端员工employee来操作的时候，才需要校验资源的访问权限
            //2.1 哪些请求需要校验权限 （答：打了自定义注解PreAuthorize权限的方法）
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
            //3.判断preAuthorize 是否有值
            if (preAuthorize == null) {
                //3.2 没有，放行  公共资源不需要校验权限
                return true;
            }
            //3.1 有，校验是否有权限访问
            String sn = preAuthorize.value();//需要校验当前登录人，是否有权限访问该资源
            if (!permissionsByRoleIds.contains(sn)) { //contains 包含的意思，有就是ture  如果没有权限就不能进去，有就直接走
                setErrorMsg(response, NO_PERMISSION); //没有权限就告诉没有权限
                return false;
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }
}
